package com.kld.shop.controller.admin;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kld.common.framework.dto.ResultMsg;
import com.kld.common.framework.global.EnumList;
import com.kld.common.framework.global.Global;
import com.kld.common.framework.page.PageInfoResult;
import com.kld.order.api.DzExceptionService;
import com.kld.order.po.DzException;
import com.kld.promotion.api.IActLogService;
import com.kld.shop.controller.base.BaseController;
import com.kld.sys.api.ISysApprovalService;
import com.kld.sys.api.ILogoperationService;
import com.kld.sys.po.SysApproval;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.math.BigDecimal;
import java.util.*;

/**
 * Created by Administrator on 2015/8/13.
 */
@Controller
@RequestMapping("/admin/billException")
public class BillExceptionController extends BaseController {

    @Autowired
    private DzExceptionService dzExceptionService;
    @Autowired
    private ILogoperationService iLogoperationService;
    @Autowired
    private ISysApprovalService approvalService;

//    @Autowired
//    private JDService jdService;
// TODO: 2016/3/29
    @Autowired
    private IActLogService actLogService;

    @RequestMapping("/billExceptionList")
    public ModelAndView billExceptionList() {
        ArrayList<String> list = GetUserFuncList();
        return new ModelAndView("admin/exception/billExceptionList", "list", list);
    }

    @RequestMapping("/exceptionApprovalList")
    public ModelAndView exceptionApprovalList() {
        ArrayList<String> list = GetUserFuncList();
        return new ModelAndView("admin/exception/exceptionApprovalList", "list", list);
    }

    @ResponseBody
    @RequestMapping("/getAllDzExceptioin")
    public ResultMsg getAllDzExceptioin() {
        String sMinfreight = request.getParameter("sMinfreight");
        String sMaxfreight = request.getParameter("sMaxfreight");
        PageHelper pageHelper = new PageHelper();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("orderid", request.getParameter("orderid"));
        map.put("ordertype", request.getParameter("ordertype"));
        map.put("cardno", request.getParameter("cardno"));
        map.put("exceptioncase", request.getParameter("exceptioncase"));
        map.put("processstate", request.getParameter("processstate"));
        map.put("createDate", request.getParameter("createDate"));
        map.put("oucode", getUserOuCode());
        map.put("oulevel", getUserOuLevel());
        if(StringUtils.isNotBlank(sMinfreight)){map.put("minfreight",Double.parseDouble(sMinfreight));}
        if(StringUtils.isNotBlank(sMaxfreight)){map.put("maxfreight",Double.parseDouble(sMaxfreight));}
        PageInfo pageInfo = null;
        try {
            pageInfo = dzExceptionService.getAllDzExceptioinList(map,getPageNum(),getPageSize());
        }catch (Exception e){
            logger.error("获取获奖名单列表错误"+e.getMessage(),e);
            e.printStackTrace();
        }
        return PageInfoResult.PageInfoMsg(pageInfo);

    }

    @ResponseBody()
    @RequestMapping(value = "processException", method = RequestMethod.POST)
    public ResultMsg processException() {
        ResultMsg rmsg = new ResultMsg();
        try {
            String state = "";
            //获取机构ID及用户id
            String userid = getUserName();
            String orgid = getUserOuCode();
            String orderId = request.getParameter("orderId");
            String processType = request.getParameter("processType");
            String processMemo = request.getParameter("processMemo");
            //1 待处理 2待审核 3 已完成 4拒绝
            //更新异常表
            int flag = dzExceptionService.updateDzExceptionById(new BigDecimal(request.getParameter("id")), Integer.parseInt(processType), processMemo, 2);
            //插入审核表
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("approvetype", 1);
            map.put("bsnsid", orderId);
            SysApproval sysApproval = approvalService.selectApprovalByBsnsid(map);
            if (sysApproval == null) {
                state = "1";
                sysApproval = new SysApproval();
                sysApproval.setApprover(userid);
                sysApproval.setApprovetime(new Date());
                sysApproval.setApprovetype(1);
                sysApproval.setBsnsid(orderId);
                sysApproval.setOucode(orgid);
                sysApproval.setState(0);
                approvalService.insert(sysApproval);
            } else {
                state = "2";
                approvalService.updateApprovalByBsnsiid(0, orderId, 1);
            }
            if (flag > 0) {
                rmsg.setResult(true);
                rmsg.setMsg("操作成功！");

                Integer operationType = Global.OPERATION_TYPE_DEFAULT;
                if ("1".equals(state)) {
                    operationType = Global.OPERATION_TYPE_ADD;
                } else if ("2".equals(state)) {
                    operationType = Global.OPERATION_TYPE_UPDATE;
                }
                //记录操作表
                Map<String, String> logmap = new HashMap<String, String>();
                logmap.put("ids", orderId);
                logmap.put("operationType", String.valueOf(operationType));
                logmap.put("opinion", processMemo);
                logmap.put("objectName", "异常交易处理");
                logmap.put("table", "dzexception");
                logmap.put("user", getUserName());
                iLogoperationService.insert(iLogoperationService.createLogperation(logmap));

            } else {
                rmsg.setResult(false);
                rmsg.setMsg("操作失败！");
            }
        } catch (Exception e) {
            logger.info("异常处理失败:"+e.getMessage(),e);
            rmsg.setResult(false);
            rmsg.setMsg("操作失败！" + e.getMessage());
        }
        return rmsg;
    }



    @ResponseBody
    @RequestMapping("/getAllDzApprovalExceptioin")
    public ResultMsg getAllDzApprovalExceptioin() {
        PageHelper pageHelper = new PageHelper();
        pageHelper.startPage(getPageNum(), getPageSize());
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("orderid", request.getParameter("orderid"));
        map.put("cardno", request.getParameter("cardno"));
        map.put("exceptioncase", request.getParameter("exceptioncase"));
        map.put("processstate", request.getParameter("processstate"));
        //审批人
        map.put("oucode", getUserOuCode());
        map.put("oulevel", getUserOuLevel());
        List<DzException> dzApprovalExceptioinList = dzExceptionService.getAllDzApprovalExceptioinList(map);
        PageInfo pageInfo = new PageInfo(dzApprovalExceptioinList);
        return PageInfoResult.PageInfoMsg(pageInfo);
    }

    @ResponseBody
    @RequestMapping("/approvalException")
    public ResultMsg approvalException() {
        ResultMsg rmsg = new ResultMsg();
        try {
            boolean tag = false;
            boolean merchanttag = true;
            boolean updactlogstate = true;
            String ids = request.getParameter("ids");
            String aids = request.getParameter("aids");
            String state = request.getParameter("state");
            String option = request.getParameter("option");
            String[] idList = ids.split(",");
            String[] aidList = aids.split(",");
            List<Integer> list = new ArrayList<Integer>();
            for (int i = 0; i < idList.length; i++) {
                list.add(new Integer(idList[i]));
            }
            List<Integer> alist = new ArrayList<Integer>();
            for (int i = 0; i < aidList.length; i++) {
                alist.add(new Integer(aidList[i]));
            }
            //更新审核表
            int flag = approvalService.updateApprovalByIds(new Integer(state), alist);
            if (flag > 0) {
                if (Integer.parseInt(state) == 1) { //代表通过审核
                    for (int i = 0; i < idList.length; i++) {
                        DzException de = dzExceptionService.getProcessTypeById(new Integer(idList[i]));
                        if (de != null) {
                            tag = true;
                            //提交给合作商下单 确认订单
                            if ("1".equals(de.getProcesstype()) && de.getOrdertype().intValue()==1) {
                                //合作商为京东
                                if (Global.TASK_MERCHANT_NAME.equals(de.getMerchantcode())) {
//                                    ResultMsg rm = jdService.confirmOrder(String.valueOf(de.getOrderid()));
                                    ResultMsg rm = new ResultMsg();
                                    // TODO: 2016/3/29 没有jdService呢
                                    if (!rm.getResult()) {
                                        merchanttag = false;
                                        logger.error("异常交易审核失败:提交给合作商" + de.getMerchantname() + "发货再次失败!!!订单号:" + de.getOrderid());
                                    }
                                }
                            }else if("3".equals(de.getProcesstype() ) && de.getOrdertype().intValue()==2){
                                List<Integer> logids = new ArrayList<Integer>();
                                logids.add(Integer.parseInt(de.getOrderid()));
                                int upd = actLogService.updatePayStates(logids, String.valueOf(EnumList.OrderState.Paied.value));
                                if(upd<=0){
                                    updactlogstate = false;
                                    rmsg.setResult(false);
                                    logger.error("异常交易审核失败:修改状态为已支付失败！抽奖记录单号:" + de.getOrderid());
                                }
                            }
                        }
                    }
                }

                if ((tag || Integer.parseInt(state) == 2) && merchanttag && updactlogstate) {
                    //更新异常数据库
                    Integer processSate = Integer.parseInt(state) + 2;
                    dzExceptionService.updateDzExceptionByIds(processSate, list);
                    rmsg.setResult(true);
                    rmsg.setMsg("操作成功！");
                    Integer operationType;
                    if ("1".equals(state)) {
                        operationType = Global.OPERATION_TYPE_PASS;
                    } else {
                        operationType = Global.OPERATION_TYPE_UNPASS;
                    }
                    //记录操作表
                    Map<String, String> logmap = new HashMap<String, String>();
                    logmap.put("ids", ids);
                    logmap.put("operationType", String.valueOf(operationType));
                    logmap.put("opinion", option);
                    logmap.put("objectName", "异常交易审核");
                    logmap.put("table", "approval");
                    logmap.put("user", getUserName());
                    iLogoperationService.insert(iLogoperationService.createLogperation(logmap));
                } else {
                    //回滚到待审核状态
                    approvalService.updateApprovalByIds(0, alist);
                    rmsg.setResult(false);
                    rmsg.setMsg("操作失败(合作商可能不存在订单号)...");
                }

            } else {
                rmsg.setResult(false);
                rmsg.setMsg("操作失败！");
            }
        } catch (Exception e) {
            logger.info("异常审核失败:"+e.getMessage(),e);
            rmsg.setResult(false);
            rmsg.setMsg("操作失败！" + e.getMessage());
        }
        return rmsg;
    }

    /**
     * 修改积分抽奖支付状态
     *
     * @return
     */
    @ResponseBody()
    @RequestMapping(value = "editState", method = RequestMethod.POST)
    public ResultMsg editState() {
        ResultMsg rmsg = new ResultMsg();
        String id = request.getParameter("id");
        String paystate = request.getParameter("paystate");
        if (StringUtils.isBlank(id)) {
            rmsg.setResult(false);
            rmsg.setMsg("请选择操作异常订单");
            return rmsg;
        }
        if (StringUtils.isBlank(paystate)) {
            rmsg.setResult(false);
            rmsg.setMsg("请选择修改状态");
            return rmsg;
        }
        DzException dzException = dzExceptionService.getDzExceptionByID(Integer.parseInt(id));
        if(dzException==null){
            rmsg.setResult(false);
            rmsg.setMsg("未找到该异常订单");
            return rmsg;
        }
            Integer processType = 3;
            String processMemo = "";
            //1 待处理 2待审核 3 已完成 4拒绝
            //更新异常表
            int upd = dzExceptionService.updateDzExceptionById(new BigDecimal(id), 3, processMemo, 2);
            if (upd <= 0) {
                rmsg.setResult(false);
                rmsg.setMsg("修改状态失败");
                return rmsg;
            }
            int flag;
            String state = "";
            //插入审核表
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("approvetype", 3);
            map.put("bsnsid", dzException.getOrderid());
            SysApproval sysApproval = approvalService.selectApprovalByBsnsid(map);
            if (sysApproval == null) {
                state = "1";
                sysApproval = new SysApproval();
                sysApproval.setApprover(getUserName());
                sysApproval.setApprovetime(new Date());
                sysApproval.setApprovetype(1);
                sysApproval.setBsnsid(dzException.getOrderid());
                sysApproval.setOucode(getUserOuCode());
                sysApproval.setState(0);
                flag = approvalService.insert(sysApproval);
            } else {
                flag = approvalService.updateApprovalByBsnsiid(0, dzException.getOrderid(), 3);
            }

            if (flag > 0) {
                rmsg.setResult(true);
                rmsg.setMsg("操作成功！");

                Integer operationType = Global.OPERATION_TYPE_DEFAULT;
                if ("1".equals(state)) {
                    operationType = Global.OPERATION_TYPE_ADD;
                } else if ("2".equals(state)) {
                    operationType = Global.OPERATION_TYPE_UPDATE;
                }
                //记录操作表
                Map<String, String> logmap = new HashMap<String, String>();
                logmap.put("ids", dzException.getOrderid());
                logmap.put("operationType", String.valueOf(operationType));
                logmap.put("opinion", processMemo);
                logmap.put("objectName", "抽奖异常交易处理");
                logmap.put("table", "dzexception");
                logmap.put("user", getUserName());
                iLogoperationService.insert(iLogoperationService.createLogperation(logmap));

            } else {
                rmsg.setResult(false);
                rmsg.setMsg("操作失败！");
            }

           /* int upd = actLogService.updatePayStates(ids, paystate);
            if(upd==ids.size()){
                rmsg.setResult(true);
                rmsg.setMsg("");
            }*/
//        }
        return rmsg;
    }
}